import React, { useEffect } from 'react';
import data from './data';
import 'tachyons';

function stringContains(str, text) {
  return str.indexOf(text) > -1;
}

const jsonUrl = (name, ver) => {
  return `http://g.alicdn.com/code/npm/@ali/${name}/${ver}/schema.json`;
};

// url  链接  但没有 图 "x-format":"@url()" link

export const isObj = (a) => stringContains(Object.prototype.toString.call(a), 'Object');

const url1 =
  'alipays://platformapi/startapp?appId=2021000196622296&page=pages/index/index?ttid=12zfb000002122alipays://platformapi/startapp?appId=2021000196622296&page=pages/index/index?ttid=12zfb000002122';

const protocolRE = /^(?:\w+:)?\/\/(\S+)$/;
// const domainRE = /^[^\s\.]+\.\S{2,}$/;

const tester =
  '{"content":{"type":"object","title":"search_form_entry","properties":{"config":{"type":"array","title":"船票搜索配置","x-config":{"type":"static"},"items":{"type":"object","title":"配置信息","properties":{"sortGroups":{"type":"array","title":"排序配置","items":{"type":"object","title":"单个排序组信息","properties":{"title":{"type":"string","title":"默认展示的名称"},"key":{"type":"string","title":"排序key"},"keys":{"type":"string","title":"排序组包含的所有key","description":"以逗号分隔"},"icon":{"type":"string","title":"默认icon"},"iconSelected":{"type":"string","title":"选中时的icon"},"clearText":{"type":"string","title":"清空排序的文案（非必须）"},"notMutex":{"type":"boolean","title":"是否不与其他筛选排序互斥"}}}},"filterGroups":{"title":"筛选配置","type":"array","items":{"type":"object","title":"单个筛选组信息","properties":{"name":{"type":"string","title":"筛选项名称"},"key":{"type":"string","title":"整个筛选项的key"},"subGroups":{"type":"array","title":"子筛选项内容","items":{"type":"object","title":"单个子筛选内容","properties":{"title":{"type":"string","title":"子筛选名称"},"key":{"type":"string","title":"子筛选key"},"keys":{"type":"string","title":"子筛选包含的所有key","description":"以逗号分隔"}}}},"icon":{"type":"string","title":"默认icon"},"iconSelected":{"type":"string","title":"选中时的icon"}}}}}}}}}}';

//  /^(?=.*(链接|地址))(?!.*图).*/

const checkImg = (schema) => {
  const title = schema.title;
  const key = schema.$id;
  let result = false;
  if (/图/.test(title)) {
    result = true;
  }
  if (/icon|img|image|pic/.test(key)) {
    result = true;
  }
  return result;
};

const checkUrl = (schema) => {
  const title = schema.title;
  const key = schema.$id;
  let result = false;
  if (/链接|地址/.test(title)) {
    result = true;
  }
  if (/url|link|href/.test(key)) {
    result = true;
  }
  if (checkImg(schema)) result = false;
  return result;
};

const wrongUrlSchema = (schema) => {
  const isUrl = checkUrl(schema);
  let formated = false;
  if (isUrl) {
    if (schema['x-format'] === '@url()') {
      formated = true;
    }
    if (schema.format === 'url') {
      formated = true;
    }
  }
  const isOk = !isUrl || (isUrl && formated);
  return !isOk;
};

const wrongImgSchema = (schema) => {
  let isImg = checkImg(schema);
  let formated = false;
  if (isImg) {
    if (schema['x-format'] === '@image()') {
      formated = true;
    }
    if (schema.format === 'image') {
      formated = true;
    }
  }
  const isOk = !isImg || (isImg && formated);
  return !isOk;
};

const getImgList = (schema, keyList = []) => {
  let _keyList = keyList;
  if (schema.type === 'object' && schema.properties) {
    Object.keys(schema.properties).forEach((key) => {
      _keyList = [..._keyList, ...getImgList(schema.properties[key])];
    });
  } else if (schema.type === 'array' && schema.items && schema.items.type === 'object') {
    const o = schema.items.properties;
    Object.keys(o).forEach((key) => {
      _keyList = [..._keyList, ...getImgList(o[key])];
    });
  } else {
    if (wrongImgSchema(schema)) keyList.push({ img: schema.$id });
    if (wrongUrlSchema(schema)) keyList.push({ url: schema.$id });
  }
  return _keyList;
};

const a = {
  b: { c: 'dev.wapa.com' },
  x: [{}, { y: 'sdfs.pre-sfdadsf.com' }],
};

const addId = (schema, name = '#') => {
  const _schema = JSON.parse(JSON.stringify(schema));
  if (isObj(_schema)) {
    Object.keys(_schema).forEach((key) => {
      _schema[key] = addId(_schema[key], key);
    });
    if (!_schema.$id) {
      _schema.$id = name;
    }
  }
  return _schema;
};

const isGood = (data) => {
  const schema = JSON.parse(data).content;
  const _schema = addId(schema);
  const imgList = getImgList(_schema);
  return imgList;
};

function App() {
  useEffect(() => {
    fetch(
      'http://g.alicdn.com/code/npm/@ali/npmmod-pcraft-explosion-2-cols-speed/1.0.22/schema.json',
    )
      .then((response) => response.json())
      .then((data) => console.log(JSON.stringify(data)));
    // const a = isUrl(url1);
    // console.log(a);
    // console.log(wrongImgSchema({ type: 'string', title: '标题', $id: 'name' }));
    console.log(isGood(tester));
  }, []);

  return (
    <ul className="list pl0 ma4">
      {data.map((item, idx) => {
        const errList = isGood(item.front_schema);
        if (errList.length === 0) return null;
        const imgList = errList.filter((item) => item.img);
        const urlList = errList.filter((item) => item.url);
        return (
          <li key={item.id} className="bt pa2">
            <div className="mb2">
              <span className="bg-blue white f6 pa1 br-100">{item.id}</span> {item.title} /{' '}
              {item.admin}
            </div>
            {imgList.length > 0 && (
              <div className="mb2">
                图片问题：<span>{JSON.stringify(imgList)}</span>
              </div>
            )}
            {urlList.length > 0 && (
              <div>
                url问题：<span>{JSON.stringify(urlList)}</span>
              </div>
            )}
          </li>
        );
      })}
    </ul>
  );
}

export default App;
